package com.yjyw.tiexie.activity.home;

import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yjyw.tiexie.R;
import com.yjyw.tiexie.bean.ABean;
import com.yjyw.tiexie.bean.BBean;
import com.yjyw.tiexie.bean.CBean;
import com.yjyw.tiexie.bean.TaskBean;
import com.yjyw.tiexie.bean.UserA;
import com.yjyw.tiexie.bean.UserB;
import com.yjyw.tiexie.bean.UserC;
import com.yjyw.tiexie.common.BaseActivity;
import com.yjyw.tiexie.common.net.HandlerCode;
import com.yjyw.tiexie.common.net.NetAPI;
import com.yjyw.tiexie.common.net.NetCallBack;
import com.yjyw.tiexie.db.DaoAUtils;
import com.yjyw.tiexie.db.DaoBUtils;
import com.yjyw.tiexie.db.DaoCUtils;
import com.yjyw.tiexie.db.UserBDBHelper;
import com.yjyw.tiexie.util.GsonUtil;
import com.yjyw.tiexie.util.LogUtil;
import com.yjyw.tiexie.util.SharedPreferencesUtils;
import com.yjyw.tiexie.util.TimeUtil;
import com.yjyw.tiexie.widget.CustomDialog;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class TaskMainActivity extends BaseActivity implements NetCallBack {
    private ImageView iv_back;
    private List<TaskBean.DataDTO.ListDTO> list = new ArrayList();
//    private UserBDBHelper mHelper;

    private TextView tv_all_num;
    private TextView tv_finish_num;

    private TextView tv_remain_num;

    private TextView tv_start_time;

    private TextView tv_end_time;

    private TextView tv_finish;

    private SurfaceView surfaceView;
    private SurfaceHolder mSurfaceHolder;

    //录像机状态标识
    private int mRecorderState;

    public static final int STATE_INIT = 0;
    public static final int STATE_RECORDING = 1;
    public static final int STATE_PAUSE = 2;

    private String currentVideoFilePath;

    private Camera mCamera;

    private MediaRecorder mediaRecorder;

    @Override
    protected int getContentView() {
        return R.layout.activity_task_main;
    }


    @Override
    protected void init() {
        // 获得数据库帮助器的实例
//        mHelper = UserBDBHelper.getInstance(this);
//        // 打开数据库帮助器的读写连接
//        mHelper.openWriteLink();
//        mHelper.openReadLink();
        iv_back = findViewById(R.id.iv_back);
        tv_all_num = findViewById(R.id.tv_all_num);
        tv_finish_num = findViewById(R.id.tv_finish_num);
        tv_remain_num = findViewById(R.id.tv_remain_num);
        tv_start_time = findViewById(R.id.tv_start_time);
        tv_end_time = findViewById(R.id.tv_end_time);
        surfaceView = (SurfaceView) findViewById(R.id.record_surfaceView);


        //配置SurfaceHolder
        mSurfaceHolder = surfaceView.getHolder();
        // 设置Surface不需要维护自己的缓冲区
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        // 设置分辨率
        mSurfaceHolder.setFixedSize(720, 480);
        // 设置该组件不会让屏幕自动关闭
        mSurfaceHolder.setKeepScreenOn(true);
        //回调接口
        mSurfaceHolder.addCallback(mSurfaceCallBack);


        tv_finish = findViewById(R.id.tv_finish);

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tv_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //弹框询问 询问以后 停止录制
                //停止视频录制
                stopRecord();
                //先给Camera加锁后再释放相机
                mCamera.lock();
                releaseCamera();
                mRecorderState = STATE_INIT;
            }
        });

        //清空B表 同步数据
//        long num = mHelper.deleteByName((String) SharedPreferencesUtils.getParam(this, "userId", ""));
        boolean result = DaoBUtils.getInstance().deleteAllUser();
        //清空A
        //清空C
        DaoAUtils.getInstance().deleteAllUser();
        DaoCUtils.getInstance().deleteAllUser();
        LogUtil.e("db", result + "");
        showProgress("");
        getTask();
        //弹框数据同步中请稍后
    }

    private SurfaceHolder.Callback mSurfaceCallBack = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder surfaceHolder) {
            initCamera();
        }

        @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
            if (mSurfaceHolder.getSurface() == null) {
                return;
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
            releaseCamera();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void getTask() {
        HashMap map = new HashMap();
        map.put("userid", SharedPreferencesUtils.getParam(this, "userId", ""));
        postJson(map, NetAPI.GET_TASK_LIST, HandlerCode.GET_TASK_LIST, this);
    }

    @Override
    public void onResponse(boolean flag, int requestCode, String result) throws Exception {
        switch (requestCode) {
            case HandlerCode.GET_TASK_LIST:
                hideProgress();
                TaskBean taskBean = (TaskBean) GsonUtil.getObject(result, TaskBean.class);
                if (taskBean.getCode() == 100 && taskBean.getData() != null) {
                    int num = taskBean.getData().getNum();//数量
                    if (taskBean.getData().getList() != null && taskBean.getData().getList().size() > 0) {
                        list.clear();
                        list.addAll(taskBean.getData().getList());
                        //获取到的本次任务数据
                        //num创建 B表数据 插入
                        //清空B表 重新生成插入数据到B表
                        for (int i = 0; i < list.size(); i++) {
                            BBean userB = new BBean();
                            userB.txBh = list.get(i).getBh();
                            userB.smTime = "";
                            userB.gps = "1";
                            userB.x = "1";
                            userB.y = "1";
                            userB.xjUser = (String) SharedPreferencesUtils.getParam(this, "userId", "");
                            userB.xjId = list.get(i).getId();//自己随机生成 暂时用list的id 到时候记得替换
                            userB.cardNo = list.get(i).getCardNo();
                            userB.smType = "1005";
                            userB.status = "良好";
                            //  xjIdStatus//巡检id更新状态 默认为0 （0/1）
                            //	xjTjStatus//默认为0  提交记录状态（0/1）
                            //	xjScanStatus//默认为0   被扫码状态（0/1）
                            //	xjEndSttatus//默认为0  巡检结束状态（0/1）
                            userB.xjIdStatus = 0;
                            userB.xjTjStatus = 0;
                            userB.xjScanStatus = 0;
                            userB.xjEndSttatus = 0;
                            DaoBUtils.getInstance().insertDefaultUser(userB);
//                            mHelper.insert(userB);
                        }
                    }

//                    List<UserB> userBS = mHelper.quertByName((String) SharedPreferencesUtils.getParam(this, "userId", ""));
                    List<BBean> userBS = DaoBUtils.getInstance().daoQueryAllUser();
                    String resultS = GsonUtil.getJson(userBS);
                    LogUtil.e("db", "插入B表的数据:" + resultS);

                    //数据获取同步完 弹框 确实是否开始巡检
                    CustomDialog dialog = new CustomDialog(this, R.style.FullScreenDialog, R.layout.medium_pop_with_title);
                    dialog.show();
                    TextView tvOk = (TextView) dialog.findViewById(R.id.ok);
                    TextView tvContent = dialog.findViewById(R.id.tv_content);
                    tvContent.setText("数据同步中请稍后...");
                    tvOk.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                            //点击同步完成 再次弹 巡检确认弹框
                            showSureDialog(num);
                        }
                    });
                }
                break;
        }
    }

    private void showSureDialog(int num) {
        //数据获取同步完 弹框 确实是否开始巡检
        CustomDialog dialog = new CustomDialog(this, R.style.FullScreenDialog, R.layout.medium_pop_with_title);
        dialog.show();
        TextView tvOk = (TextView) dialog.findViewById(R.id.ok);
        TextView tvContent = dialog.findViewById(R.id.tv_content);
        tvContent.setText("确定【开始作业】？");
        tvOk.setText("确定");
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //点击确定  开始巡检 录制视频
                dialog.dismiss();
                tv_all_num.setText(num + "");
                tv_finish_num.setText("0");
                tv_remain_num.setText(num + "");
                tv_start_time.setText(TimeUtil.getTime());
                //巡检开始语音提示
                //A表插入数据 更新开始时间
                ABean userA = new ABean();
                userA.xjStart = TimeUtil.getTime();
                userA.xjEndTime = "";
                userA.xjUser = (String) SharedPreferencesUtils.getParam(TaskMainActivity.this, "userId", "");
                userA.xjCounts = num; // 总数
                userA.xjNums = 0;//被扫到的总数
                userA.ylNum = num;//没扫到的
                userA.remark = "";
                userA.bdIdstatus = 0;
                userA.bdStatus = 0;
                userA.bdId = "";

                DaoAUtils.getInstance().insertOrReplace(userA);
                //“bdId” ：“0” //巡检id   自己生成
//                mHelper.insertA(userA);
//                List<UserA> userAS = mHelper.quertByNameA((String) SharedPreferencesUtils.getParam(TaskMainActivity.this, "userId", ""));
                List<ABean> userAS = DaoAUtils.getInstance().daoQueryAllUser();
                String resultS = GsonUtil.getJson(userAS);
                LogUtil.e("db", "插入A表的数据:" + resultS);

                //开始录制  将视频存到本地路径 xjId.mp4  存入c表
                startIt();
            }
        });
    }

    private void startIt() {
        if (mRecorderState == STATE_INIT) {

            if (getSDPath(getApplicationContext()) == null)
                return;
            //视频文件保存路径，configMediaRecorder方法中会设置
            currentVideoFilePath = getSDPath(getApplicationContext()) + getVideoName();
            //开始录制  将视频存到本地路径 xjId.mp4  存入c表
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    CBean userC = new CBean();
                    userC.fileName = "";
                    userC.filePath = currentVideoFilePath;
                    userC.xjUser = (String) SharedPreferencesUtils.getParam(TaskMainActivity.this, "userId", "");
                    userC.bdId = "";
                    userC.serverFilePath = "";
                    userC.bdIdstatus = 0;
                    userC.upFileStatus = 0;
                    userC.upFileRecordStatus = 0;

                    DaoCUtils.getInstance().insertOrReplace(userC);
//                    mHelper.insertC(userC);
//                    List<UserC> userCS = mHelper.quertByNameC((String) SharedPreferencesUtils.getParam(TaskMainActivity.this, "userId", ""));
                    List<CBean> userCS = DaoCUtils.getInstance().daoQueryAllUser();
                    String resultS = GsonUtil.getJson(userCS);
                    LogUtil.e("db", "插入C表的数据:" + resultS);
                }
            }, 500);

            //开始录制视频
            if (!startRecord())
                return;
//            refreshControlUI();
            mRecorderState = STATE_RECORDING;

        }
    }

    /**
     * 开始录制视频
     */
    public boolean startRecord() {

        initCamera();
        //录制视频前必须先解锁Camera
        mCamera.stopPreview();
        mCamera.unlock();
        configMediaRecorder();
        try {
            //开始录制
            mediaRecorder.prepare();
            mediaRecorder.start();
        } catch (IOException e) {
            return false;
        }
        return true;
    }


    /**
     * 初始化摄像头
     *
     * @throws IOException
     * @author liuzhongjun
     */
    private void initCamera() {

        if (mCamera != null) {
            releaseCamera();
        }

        mCamera = Camera.open();
        if (mCamera == null) {
            Toast.makeText(this, "未能获取到相机！", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            //将相机与SurfaceHolder绑定
            mCamera.setPreviewDisplay(mSurfaceHolder);
            //配置CameraParams
            configCameraParams();
            //启动相机预览
            mCamera.startPreview();
        } catch (IOException e) {
            //有的手机会因为兼容问题报错，这就需要开发者针对特定机型去做适配了
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }

    /**
     * 设置摄像头为竖屏
     *
     * @author lip
     * @date 2015-3-16
     */
    private void configCameraParams() {
        Camera.Parameters params = mCamera.getParameters();
        //设置相机的横竖屏(竖屏需要旋转90°)
        if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
            params.set("orientation", "portrait");
            mCamera.setDisplayOrientation(90);
        } else {
            params.set("orientation", "landscape");
            mCamera.setDisplayOrientation(0);
        }
        params.setPreviewSize(720, 480);
        //设置聚焦模式
        params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
        //缩短Recording启动时间
        params.setRecordingHint(true);
        //影像稳定能力
        if (params.isVideoStabilizationSupported())
            params.setVideoStabilization(true);

        for (int i = 0; i < params.getSupportedPreviewSizes().size(); i++) {
            Log.e("size", params.getSupportedPreviewSizes().get(i).width + "x" + params.getSupportedPreviewSizes().get(i).height);
        }
        List<Integer> previewFormats = mCamera.getParameters().getSupportedPreviewFormats();
        for (int i = 0; i < previewFormats.size(); i++) {
            Log.e("previewFormats", previewFormats.get(i).toString());
        }
        mCamera.setParameters(params);
    }

    /**
     * 释放摄像头资源
     *
     * @author liuzhongjun
     * @date 2016-2-5
     */
    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }


    @Override
    public void tokenTimeOut(int requestCode) {

    }

    /**
     * 配置MediaRecorder()
     */

    private void configMediaRecorder() {
        mediaRecorder = new MediaRecorder();
        mediaRecorder.reset();
        mediaRecorder.setCamera(mCamera);
        mediaRecorder.setOnErrorListener(OnErrorListener);

        //使用SurfaceView预览
        mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());

        //1.设置采集声音
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        //设置采集图像
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        //2.设置视频，音频的输出格式 mp4
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
        //3.设置音频的编码格式
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        //设置图像的编码格式
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        //设置立体声
//        mediaRecorder.setAudioChannels(2);
        //设置最大录像时间 单位：毫秒
//        mediaRecorder.setMaxDuration(60 * 1000);
        //设置最大录制的大小 单位，字节
//        mediaRecorder.setMaxFileSize(1024 * 1024);
        //音频一秒钟包含多少数据位
        CamcorderProfile mProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_480P);
        mediaRecorder.setAudioEncodingBitRate(44100);
        if (mProfile.videoBitRate > 2 * 1024 * 1024)
            mediaRecorder.setVideoEncodingBitRate(2 * 1024 * 1024);
        else
            mediaRecorder.setVideoEncodingBitRate(1024 * 1024);
        mediaRecorder.setVideoFrameRate(mProfile.videoFrameRate);

        //设置选择角度，顺时针方向，因为默认是逆向90度的，这样图像就是正常显示了,这里设置的是观看保存后的视频的角度
        mediaRecorder.setOrientationHint(90);
        //设置录像的分辨率
        mediaRecorder.setVideoSize(720, 480);

        //设置录像视频输出地址
        mediaRecorder.setOutputFile(currentVideoFilePath);
    }

    /**
     * 创建视频文件保存路径
     */
    public static String getSDPath(Context context) {
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            Toast.makeText(context, "请查看您的SD卡是否存在！", Toast.LENGTH_SHORT).show();
            return null;
        }

        File sdDir = Environment.getExternalStorageDirectory();
        File eis = new File(sdDir.toString() + "/RecordVideo/");
        if (!eis.exists()) {
            eis.mkdir();
        }
        return sdDir.toString() + "/RecordVideo/";
    }

    private String getVideoName() {
        return "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".mp4";
    }

    private MediaRecorder.OnErrorListener OnErrorListener = new MediaRecorder.OnErrorListener() {
        @Override
        public void onError(MediaRecorder mediaRecorder, int what, int extra) {
            try {
                if (mediaRecorder != null) {
                    mediaRecorder.reset();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 停止录制视频
     */
    public void stopRecord() {
        // 设置后不会崩
        mediaRecorder.setOnErrorListener(null);
        mediaRecorder.setPreviewDisplay(null);
        //停止录制
        mediaRecorder.stop();
        mediaRecorder.reset();
        //释放资源
        mediaRecorder.release();
        mediaRecorder = null;
    }
}
